<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    // 利用栈的只是解决该问题
    let str = '2[2[a]5[b]]';

    function smartRepeat(templateStr) {
      // 指针
      let index = 0;
      // 两个栈
      let stack1 = [];
      let stack2 = [];

      // 剩余部分
      let rest = templateStr;
      // 遍历
      while (index < templateStr.length - 1) {
        // 保存剩余部分
        rest = templateStr.substring(index);
        if (/^\d+\[/.test(rest)) {
          // 得到数字
          let times = Number(rest.match(/^(\d+)\[/)[1]);
          // 压栈
          stack1.push(times);
          stack2.push('');
          // times为数字，+1是要跳过[
          index += times.toString().length + 1;
        } else if (/^\w+\]/.test(rest)) {
          let word = rest.match(/^(\w+)\]/)[1];
          stack2[stack2.length - 1] = word
          index += word.length;
        } else {
          // 为]的情况
          // 栈1和栈2最后一个出栈，栈1弹出的数字就是要复制栈2字母的倍数
          // 将栈2最后的字符串追加弹出栈所组合的字符串
          let times = stack1.pop();
          let word = stack2.pop();
          let newWord = word.repeat(times);
          stack2[stack2.length - 1] += newWord;
          index++;
        }
      }
      // 返回最后一项
      return stack2[0].repeat(stack1[0])
    }

    let result = smartRepeat(str);
    console.log(result);
  </script>
</body>

</html>